package com.cyf.service.impl;

import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.cyf.db.bean.ad.Ad;
import com.cyf.db.bean.ad.AdOrderProcess;
import com.cyf.db.bean.ad.AdPayOrder;
import com.cyf.db.mapper.*;
import com.cyf.db.mapper.ad.AdMapper;
import com.cyf.db.mapper.ad.AdOrderProcessMapper;
import com.cyf.db.mapper.ad.AdPayOrderMapper;
import com.cyf.db.mapper.ad.AdPlanMapper;
import com.cyf.pay.alipay.service.AlipayService;
import com.cyf.pay.wxpay.bean.WxpayQueryOrderReq;
import com.cyf.pay.wxpay.bean.WxpayQueryOrderRsp;
import com.cyf.pay.wxpay.service.WxpayService;
import com.cyf.service.AdPayOrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Date;

/**
 * 广告支付订单
 * Created by hfy on 2017/5/16.
 */
@Service
public class AdPayOrderServiceImpl implements AdPayOrderService {

    private static final Logger logger = LoggerFactory.getLogger(AdPayOrderServiceImpl.class);

    @Autowired
    private AdPayOrderMapper adPayOrderMapper;
    @Autowired
    private AdMapper adMapper;
    @Autowired
    private AdPlanMapper adPlanMapper;
    @Autowired
    private InviteCodeMapper inviteCodeMapper;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private WxpayService wxpayService;
    @Autowired
    private AdOrderProcessMapper adOrderProcessMapper;

    @Override
    @Transactional(rollbackFor = java.lang.Exception.class)
    public synchronized void payFinish(AdPayOrder adPayOrder, Integer payStatus, String tradeNo, Integer settleFee, Date settleDate) {
        AdPayOrder adPayOrderById = adPayOrderMapper.getById(adPayOrder.getId());
        if (adPayOrderById.getStatus() == AdPayOrder.STATUS_WAIT_REVIEW) {
            logger.info("状态已经是等待审核中，所以直接返回更新支付状态成功！");
            return;
        }
        // 更新支付账单
        adPayOrder.setQueryId(tradeNo);
        adPayOrder.setStatus(payStatus);
        adPayOrder.setSettleAmt(settleFee);
        adPayOrder.setSettleDate(settleDate);
        adPayOrderMapper.updatePayOrder(adPayOrder);
        Ad ad = adMapper.getById(adPayOrder.getAdId());

        AdOrderProcess adOrderProcess = new AdOrderProcess();
        adOrderProcess.setPayOrderNo(adPayOrder.getId());

        if (payStatus == AdPayOrder.STATUS_WAIT_PAY) {
            // 1.更新广告的邀请码字段
            adMapper.updateInviteCodeId(ad.getId(), null);
            if (ad.getInviteCodeId() != null && 0 != ad.getInviteCodeId()) {
                inviteCodeMapper.updateUseornot(ad.getInviteCodeId(), 1);
            }
            adPlanMapper.updateStatusByAdId(ad.getId(), 0);

            /*adOrderProcess.setCreatedTime(new Date());
            adOrderProcess.setDescInfo("支付失败");
            adOrderProcess.setStatus(AdPayOrder.STATUS_CLOSE);*/
        } else {
            // 1.更新广告的支付状态
            adMapper.updatePaySuccess(ad.getId(), settleFee);

            adPlanMapper.updateStatusByAdId(ad.getId(), 1);
            if (ad.getInviteCodeId() != null && 0 != ad.getInviteCodeId()) {
                inviteCodeMapper.updateUseornot(ad.getInviteCodeId(), 0);
            }

//            adOrderProcess.setDescInfo("支付成功");
            adOrderProcess.setCreatedTime(settleDate);
            adOrderProcess.setStatus(AdPayOrder.STATUS_WAIT_REVIEW);
            adOrderProcessMapper.insertAdOrderProcess(adOrderProcess);
        }

    }

    @Override
    public void updatePayOrderStatus(AdPayOrder adPayOrder) {
        switch (adPayOrder.getPayWay()) {
            case AdPayOrder.PAYWAY_WECHAT:
                updateWxpayOrderStatus(adPayOrder);
                break;
            case AdPayOrder.PAYWAY_ALIPAY:
                updateAlipayOrderStatus(adPayOrder);
                break;
            case AdPayOrder.PAYWAY_BALANCE:
                break;
            default:
                break;
        }
    }

    /**
     * 查询支付宝支付的广告订单的支付状态，并更新支付状态
     * @param adPayOrder 广告支付订单
     */
    private void updateAlipayOrderStatus(AdPayOrder adPayOrder) {

        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        if (StringUtils.isEmpty(adPayOrder.getQueryId()) || "0".equals(adPayOrder.getQueryId())) {
            model.setOutTradeNo(adPayOrder.getOrderNo());
        } else {
            model.setTradeNo(adPayOrder.getQueryId());
        }
        AlipayTradeQueryResponse alipayTradeQueryResponse = alipayService.queryOrder(model);
        if ("ACQ.TRADE_NOT_EXIST".equals(alipayTradeQueryResponse.getSubCode()) && (new Date().getTime() - adPayOrder.getTxnTime().getTime() < 30 * 60 * 1000)) {
            return;
        }
        if (alipayTradeQueryResponse.isSuccess()) {
//            WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
            if ("WAIT_BUYER_PAY".equals(alipayTradeQueryResponse.getTradeStatus())) {
                logger.info("等待买家支付！");
                return;
            }
            if ("TRADE_SUCCESS".equals(alipayTradeQueryResponse.getTradeStatus()) || "TRADE_FINISHED".equals(alipayTradeQueryResponse.getTradeStatus())) {
                payFinish(adPayOrder, AdPayOrder.STATUS_WAIT_REVIEW, alipayTradeQueryResponse.getTradeNo(), (int) (Double.parseDouble(alipayTradeQueryResponse.getReceiptAmount()) * 100), alipayTradeQueryResponse.getSendPayDate());
                return;
            }
        }
        int totalAmount = 0;
        if (!StringUtils.isEmpty(alipayTradeQueryResponse.getTotalAmount())) {
            totalAmount = (int) (Double.parseDouble(alipayTradeQueryResponse.getReceiptAmount()) * 100);
        }
        //payFinish(adPayOrder, AdPayOrder.STATUS_WAIT_PAY, alipayTradeQueryResponse.getTradeNo(), totalAmount, new Date());
    }

    /**
     * 查询支付宝支付的广告订单的支付状态，并更新支付状态
     * @param adPayOrder  广告支付订单
     */
    private void updateWxpayOrderStatus(AdPayOrder adPayOrder) {
        WxpayQueryOrderReq wxpayQueryOrderReq = new WxpayQueryOrderReq();
        if (StringUtils.isEmpty(adPayOrder.getQueryId()) || "0".equals(adPayOrder.getQueryId())) {
            wxpayQueryOrderReq.setOut_trade_no(adPayOrder.getOrderNo());
        } else {
            wxpayQueryOrderReq.setTransaction_id(adPayOrder.getQueryId());
        }
        WxpayQueryOrderRsp wxpayQueryOrderRsp = wxpayService.queryOrder(wxpayQueryOrderReq);
        logger.info("微信支付查询结果：{}", wxpayQueryOrderRsp);
        if (WxpayQueryOrderRsp.SUCCESS.equals(wxpayQueryOrderRsp.getReturn_code()) && WxpayQueryOrderRsp.SUCCESS.equals(wxpayQueryOrderRsp.getResult_code())) {
            if (WxpayQueryOrderRsp.TRADE_STATE_SUCCESS.equals(wxpayQueryOrderRsp.getTrade_state())) {
                Date payDate = new Date();
                try {
                    payDate = WxpayQueryOrderRsp.TIME_END_FORMAT.parse(wxpayQueryOrderRsp.getTime_end());
                } catch (ParseException e) {
                    logger.error("更新微信支付账单时，时间格式化异常：{}", e);
                }
                payFinish(adPayOrder, AdPayOrder.STATUS_WAIT_REVIEW, wxpayQueryOrderRsp.getTransaction_id(), wxpayQueryOrderRsp.getTotal_fee(), payDate);
            } else if (WxpayQueryOrderRsp.TRADE_STATE_PAYERROR.equals(wxpayQueryOrderRsp.getTrade_state()) || WxpayQueryOrderRsp.TRADE_STATE_CLOSED.equals(wxpayQueryOrderRsp.getTrade_state())) {
                //payFinish(adPayOrder, AdPayOrder.STATUS_WAIT_PAY, wxpayQueryOrderRsp.getTransaction_id(), wxpayQueryOrderRsp.getTotal_fee(), new Date());
            } else {
                // 不更新支付账单
            }
        } else {
            logger.debug("不更新支付账单！");
        }
    }
}
